import os
import torch
import torch.nn as nn
from torchvision import datasets, transforms, models
from torch.utils.data import DataLoader
from torch.optim import Adam
import matplotlib.pyplot as plt
os.environ['KMP_DUPLICATE_LIB_OK']='True'
# 设置设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

# 数据增强和预处理
transform = transforms.Compose([
    transforms.Resize((224, 224)),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])

# 加载数据集
train_data = datasets.ImageFolder(r'F:\pythonProject\Alexnet\pizza\train', transform=transform)
val_data = datasets.ImageFolder(r'F:\pythonProject\Alexnet\pizza\test', transform=transform)

train_loader = DataLoader(train_data, batch_size=32, shuffle=True)
val_loader = DataLoader(val_data, batch_size=32, shuffle=False)

# 定义模型
class AlexNet(nn.Module):
    def __init__(self, num_classes=3):  # 修改为3，适应三分类问题
        super(AlexNet, self).__init__()
        self.model = models.alexnet(weights=models.AlexNet_Weights.DEFAULT)
        self.model.classifier[6] = nn.Linear(4096, num_classes)

    def forward(self, x):
        return self.model(x)

# 实例化模型
model = AlexNet(num_classes=3).to(device)

# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = Adam(model.parameters(), lr=0.0001)

# 记录损失和准确率
train_losses = []
val_losses = []

# 训练函数
def train(model, train_loader, criterion, optimizer, epoch):
    model.train()
    running_loss = 0.0
    correct = 0
    total = 0
    for inputs, labels in train_loader:
        inputs, labels = inputs.to(device), labels.to(device)

        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        running_loss += loss.item()
        _, predicted = torch.max(outputs, 1)
        total += labels.size(0)
        correct += (predicted == labels).sum().item()

    epoch_loss = running_loss / len(train_loader)
    accuracy = 100 * correct / total
    train_losses.append(epoch_loss)  # 记录训练损失
    print(f"Epoch [{epoch + 1}], Loss: {epoch_loss:.4f}, Accuracy: {accuracy:.2f}%")

# 验证函数
def validate(model, val_loader, criterion):
    model.eval()
    running_loss = 0.0
    correct = 0
    total = 0
    with torch.no_grad():
        for inputs, labels in val_loader:
            inputs, labels = inputs.to(device), labels.to(device)
            outputs = model(inputs)
            loss = criterion(outputs, labels)

            running_loss += loss.item()
            _, predicted = torch.max(outputs, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

    val_loss = running_loss / len(val_loader)
    accuracy = 100 * correct / total
    val_losses.append(val_loss)  # 记录验证损失
    print(f"Validation Loss: {val_loss:.4f}, Validation Accuracy: {accuracy:.2f}%")
    return accuracy

# 训练和验证过程
def main():
    num_epochs = 10
    best_accuracy = 0.0

    for epoch in range(num_epochs):
        train(model, train_loader, criterion, optimizer, epoch)
        accuracy = validate(model, val_loader, criterion)

        if accuracy > best_accuracy:
            best_accuracy = accuracy
            torch.save(model.state_dict(), 'models/alexnet_best.pth')
            print(f"Best model saved at epoch {epoch + 1} with accuracy: {best_accuracy:.2f}%")

    # 绘制损失曲线
    plt.figure(figsize=(10, 5))
    plt.plot(train_losses, label='Training Loss')
    plt.plot(val_losses, label='Validation Loss')
    plt.title('Training and Validation Loss')
    plt.xlabel('Epoch')
    plt.ylabel('Loss')
    plt.legend()
    plt.grid()
    plt.savefig('img/loss_curve.png')  # 保存损失曲线图
    plt.show()  # 显示图形

# 启动训练
if __name__ == "__main__":
    main()